import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Card,
  Form,
  Table,
  message,
  Row,
  Col,
  Select,
  Button,
  Input,
  DatePicker,
  Modal,
  InputNumber,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { Link, routerRedux } from 'dva/router';
import { getParamUrl, myMessage, getUniqueKey } from '../../utils/formatDataSource';
import ClassInfoStudentSearch from './ClassInfoStudentSearch';
import TeacherCalendarSearchInput from './TeacherCalendarSearchInput';
// import store from '../../index';
const Option = Select.Option;
const moment = require('moment');

@connect(({ classInfo3, administration3, loading }) => ({
  classInfo:classInfo3,
  administration:administration3,
}))
@Form.create()
class ClassInfoEdit extends PureComponent {
  componentDidMount() {
    this.initLoad();
  }
  state = {
    subjectList: [],
    classLevelList: [],
    campusList: [],
    selectedStudent: {},
    studentList: [],
    classInfo: {},
    updateTeacherVisible: false,
    selectedTeacher: {},
    chooseTeacher: {},
    needStudent: [],
    selectedId: 0,
    uniqueModalKey: getUniqueKey(10),
    classTypeList: [],
  };
  initLoad = () => {
    const { dispatch, location: { search } } = this.props;
    const params = getParamUrl(search);
    // 科目list
    dispatch({
      type: 'classInfo3/getSubjectList',
    }).then(() => {
      this.setState({
        subjectList: this.props.classInfo.subjectList,
      });
    });
    dispatch({
      type: 'classInfo3/getClassLevel',
    }).then(() => {
      this.setState({
        classLevelList: this.props.classInfo.classLevelList,
      });
    });
    dispatch({
      type: 'administration3/getCampusList',
    }).then(() => {
      this.setState({
        campusList: this.props.administration.campusList,
      });
    });
    dispatch({
      type: 'classInfo3/getClassInfo',
      payload: 'classId=' + params.classId,
    }).then(() => {
      this.getStudents(this.props.classInfo.classInfo);
      this.setState({
        classInfo: this.props.classInfo.classInfo,
        studentList: this.props.classInfo.classInfo.studentList,
      });
    });
    dispatch({
      type: 'classInfo3/getClassTypeList',
    }).then(() => {
      this.setState({
        classTypeList: this.props.classInfo.classTypeList,
      });
    });
  };
  getStudents = classInfo => {
    this.props
      .dispatch({
        type: 'classInfo3/getNeedStudentList',
        payload: 'classType=' + classInfo.type + '&subject=' + classInfo.subject,
      })
      .then(() => {
        const { needStudent } = this.props.classInfo;
        const { studentList = [] } = this.props.classInfo.classInfo;
        const filetStudent = needStudent.filter(n => {
          const exist = studentList.find(s => s.id === n.id);
          return exist ? false : true;
        });
        filetStudent.map(n => (n.leftTime = n.totalTime - n.classTime));
        this.setState({
          needStudent: filetStudent,
        });
      });
  };
  selectStudent = student => {
    this.setState({
      selectedStudent: student,
    });
  };
  selectTeacher = teacher => {
    this.setState({
      chooseTeacher: teacher,
    });
  };
  handleAddCreate = () => {
    const { studentList, needStudent, selectedId } = this.state;
    const exist = needStudent.find(s => s.id === selectedId);
    const newArr = needStudent.filter(s => s.id !== selectedId);
    studentList.push(exist);
    this.setState({
      studentList: studentList,
      addStudentVisible: false,
      needStudent: newArr,
      uniqueModalKey: getUniqueKey(10),
    });
  };
  handleAddCancel = () => {
    this.setState({
      addStudentVisible: false,
      uniqueModalKey: getUniqueKey(10),
    });
  };
  removeStudent = (index, item) => {
    const { studentList, needStudent } = this.state;
    const newStudentList = studentList.filter(s => s.id !== item.id);
    needStudent.push(item);
    needStudent.sort((a, b) => a.id - b.id);
    this.setState({
      studentList: newStudentList,
      needStudent: [...needStudent],
    });
  };
  submitClassInfo = e => {
    e.preventDefault();
    const { dispatch } = this.props;
    const { classInfo, selectedTeacher, studentList } = this.state;
    this.props.form.validateFields((err, values) => {
      if (err) {
        console.log('Received values of form: ', values);
        return;
      }

      values.teacherId = selectedTeacher.id || classInfo.teacherId;
      values.studentList = studentList;
      values.id = classInfo.id;
      values.startDate = values.classRangeTime[0].toDate();
      values.endDate = values.classRangeTime[1].toDate();
      dispatch({
        type: 'classInfo3/updateClassInfo',
        payload: values,
      }).then(() => {
        const { updateClassResponse } = this.props.classInfo;
        if (updateClassResponse && updateClassResponse.data == 1) {
          myMessage.success('班级修改成功', 3);
          // const { dispatch } = store;
          this.dispatch(routerRedux.push('/administration/classInfo'));
        } else {
          myMessage.error('班级修改失败', 3);
        }
      });
    });
  };
  handleUpdateTeacherCancel = () => {
    this.setState({
      updateTeacherVisible: false,
    });
  };
  handleUpdateTeacher = () => {
    this.setState({
      selectedTeacher: this.state.chooseTeacher,
      updateTeacherVisible: false,
    });
  };
  showUpdateTeacher = () => {
    this.setState({
      updateTeacherVisible: true,
    });
  };
  classTypeSelect = v => {
    const { classInfo } = this.state;
    classInfo.type = v;
  };
  subjectSelect = v => {
    const { classInfo } = this.state;
    classInfo.subject = v;
  };
  studentChange = value => {
    this.setState({ selectedId: value });
  };
  studentFocus = () => {};
  studentBlur = () => {};
  render() {
    const FormItem = Form.Item;
    const { getFieldDecorator } = this.props.form;
    const {
      addStudentVisible,
      updateTeacherVisible,
      studentList,
      classInfo,
      selectedTeacher,
    } = this.state;
    const { campusList } = this.props.administration;
    const { subjectList, classLevelList } = this.props.classInfo;
    const RangePicker = DatePicker.RangePicker;
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
    };
    return (
      <PageHeaderLayout>
        <Card>
          <Form onSubmit={this.submitClassInfo}>
            <Row>
              <Col span={8}>
                <h3>班级信息</h3>
              </Col>
              <Col span={16} style={{ textAlign: 'right' }}>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => this.props.dispatch(routerRedux.push('/administration/classInfo'))}
                >
                  返回
                </Button>
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                <FormItem labelCol={{ span: 2 }} wrapperCol={{ span: 22 }} label="班级名称">
                  {getFieldDecorator('name', {
                    initialValue: classInfo.name,
                    rules: [{ required: true, message: '请填写班级名称' }],
                  })(<Input placeholder="班级名称" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem {...formItemLayout} label="选择科目">
                  {getFieldDecorator('subject', {
                    initialValue: classInfo.subject,
                    rules: [{ required: true, message: '请选择科目' }],
                  })(
                    <Select onSelect={this.subjectSelect}>
                      {subjectList.map((item, index) => {
                        return (
                          <Option key={index} value={item.code}>
                            {item.msg}
                          </Option>
                        );
                      })}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem {...formItemLayout} label="选择校区">
                  {getFieldDecorator('campusId', {
                    initialValue: classInfo.campusId,
                    rules: [{ required: true, message: '请选择校区' }],
                  })(
                    <Select>
                      {campusList.map((item, index) => {
                        return (
                          <Option value={item.id} key={index}>
                            {item.name}
                          </Option>
                        );
                      })}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem {...formItemLayout} label="选择年级">
                  {getFieldDecorator('classLevel', {
                    initialValue: classInfo.classLevel,
                    rules: [{ required: true, message: '请选择年级' }],
                  })(
                    <Select>
                      {classLevelList.map((item, index) => {
                        return (
                          <Option key={index} value={item.code}>
                            {item.msg}
                          </Option>
                        );
                      })}
                    </Select>
                  )}
                </FormItem>
              </Col>

              <Col span={12}>
                <FormItem {...formItemLayout} label="选择老师">
                  {getFieldDecorator('teacherId', {
                    initialValue: selectedTeacher.name || classInfo.teacherName,
                  })(<input disabled="disabled" />)}{' '}
                  &nbsp;&nbsp;<Button onClick={this.showUpdateTeacher}>修改老师</Button>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem {...formItemLayout} label="课程类型">
                  {getFieldDecorator('type', {
                    initialValue: classInfo.type,
                    rules: [{ required: true, message: '请选择课程类型' }],
                  })(
                    <Select onSelect={this.classTypeSelect}>
                      {this.state.classTypeList.map(t => (
                        <Option value={t.id} key={t.id}>
                          {t.name}
                        </Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem {...formItemLayout} label="授课时间">
                  {getFieldDecorator('classRangeTime', {
                    initialValue: [moment(classInfo.startDate), moment(classInfo.endDate)],
                    rules: [{ required: true, message: '请选择授课时间' }],
                  })(<RangePicker span={12} showTime format="YYYY-MM-DD HH:mm:ss" />)}
                </FormItem>
              </Col>
            </Row>
            <h3>班级学生</h3>
            {studentList.map((item, index) => (
              <Row key={index}>
                <Col span={8}>{item.name}</Col>
                <Col span={8}>剩余课时 {item.leftTime}</Col>
                <Col span={8}>
                  <Button
                    onClick={() => {
                      this.removeStudent(index, item);
                    }}
                  >
                    移出学生
                  </Button>
                </Col>
              </Row>
            ))}
            <FormItem>
              <Row>
                <Col span={8} offset={8}>
                  <Button
                    onClick={() => {
                      this.setState({ addStudentVisible: true });
                    }}
                  >
                    添加学生
                  </Button>
                </Col>
              </Row>
            </FormItem>
            <FormItem>
              <Button type="primary" htmlType="submit">
                提 交
              </Button>
            </FormItem>
          </Form>
        </Card>
        <Modal
          key={this.state.uniqueModalKey}
          visible={addStudentVisible}
          title="请输入需要添加的学生名称"
          okText="确定"
          onCancel={this.handleAddCancel}
          onOk={this.handleAddCreate}
        >
          {/* <ClassInfoStudentSearch classType={classInfo.type} subject={classInfo.subject}  onOk={this.selectStudent}/> */}
          <Select
            showSearch
            style={{ width: 200 }}
            placeholder="请选择学生"
            optionFilterProp="children"
            onChange={this.studentChange}
            onFocus={this.studentFocus}
            onBlur={this.studentBlur}
            filterOption={(input, option) =>
              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {this.state.needStudent.map((s, i) => (
              <Option value={s.id} key={i}>
                {s.name}
              </Option>
            ))}
          </Select>
        </Modal>
        <Modal
          visible={updateTeacherVisible}
          title="请输入需要修改的老师姓名"
          okText="修改"
          onCancel={this.handleUpdateTeacherCancel}
          onOk={this.handleUpdateTeacher}
        >
          <TeacherCalendarSearchInput myStyle={150} subject="" onOk={this.selectTeacher} />
        </Modal>
      </PageHeaderLayout>
    );
  }
}

export default ClassInfoEdit;
